'use strict';
const crypto = require('crypto')
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const secret = 'com.mw.etalk' // 自己的密钥不要直接使用示例值，且注意不要泄露
	const hmac = crypto.createHmac('sha256', secret);

	let params = event.queryStringParameters
	const sign = params.sign
	delete params.sign
	const signStr = Object.keys(params).sort().map(key => {
		return `${key}=${params[key]}`
	}).join('&')

	hmac.update(signStr);
	var signResult = hmac.digest('hex')
	if (sign !== signResult) {
		throw new Error('非法访问sign:' + signResult + ',string:' + signStr)
	}
	
	const {
		phone,
		templateId
	} = params

	try {
		const res = await uniCloud.sendSms({
			appid: '__UNI__FAED04E',
			phone: phone,
			templateId: templateId, // 请替换为自己申请的模板id
			data: params
		})
		console.log(res, params)
		// 返回手机号给自己服务器
		return res
	} catch (err) {
		// 调用失败
		console.log(err.errCode)
		console.log(err.errMsg)
		return {
			code: err.errCode,
			msg: err.errMsg
		}
	}

};